package com.shareach.web.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.benayn.ustyle.Reflecter;
import com.google.common.collect.Maps;
import com.shareach.common.BaseQueryOrder;
import com.shareach.dao.redis.impl.DeployRDao;
import com.shareach.dao.redis.impl.DeployRDao.DeployType;
import com.shareach.domain.BaseBrandDomain;
import com.shareach.domain.BaseCityDomain;
import com.shareach.service.BaseBrandService;
import com.shareach.service.BaseCityService;
import com.shareach.util.JsonUtil;
import com.shareach.web.basic.Answer;

@Controller("wbrand")
@RequestMapping("/wbrand")
public class BrandController extends BaseController {
	@Autowired
	private BaseBrandService brandService;
	@Autowired
	private BaseCityService cityService;

	@Autowired
	private DeployRDao deployRDao;

	@RequestMapping(value = "/index.htm")
	public ModelAndView summary(HttpServletRequest request, String name, String city) {
		ModelAndView mv = new ModelAndView("admin/shop/brand/index");

		BaseQueryOrder order = new BaseQueryOrder();
		order.setNumber(getPageNo(request).toString());
		order.setPageSize(getPageSize(request));
		order.addSort("_id", Order.DESCENDING.toString());
		BaseBrandDomain brandDomain = new BaseBrandDomain();

		if (!StringUtils.isEmpty(name)) {
			brandDomain.setName(name);
			mv.addObject("name", name);
		}

		if (!StringUtils.isEmpty(city)) {
			brandDomain.setCity(Long.valueOf(city));
		}

		Page<BaseBrandDomain> result = brandService.getPageResult(brandDomain, order);

		List<BaseCityDomain> cities = cityService.findAll();
		mv.addObject("cities", cities);
		mv.addObject("result", result);

		return mv;
	}

	@RequestMapping(value = "/detail.htm")
	public ModelAndView detail(HttpServletRequest request, Long brandId) {
		ModelAndView mv = new ModelAndView("admin/shop/brand/detail");

		// shop
		BaseBrandDomain domBrand = brandService.getById(brandId);
		Map<String, Object> brand = asDynabean(domBrand);
		mv.addObject("brand", brand);
		return mv;
	}

	@RequestMapping(value = "/upload.htm", method = RequestMethod.POST)
	public ModelAndView upload(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") MultipartFile file) {
		if (!file.isEmpty()) {
			String newFileName = uploadFile(request, file, DeployType.ShopBrand.getDesc());

			// update shop
			Long brandId = Long.valueOf(request.getParameter("brandId"));
			BaseBrandDomain categoryDom = new BaseBrandDomain();
			categoryDom.setId(brandId);
			categoryDom.setIcon(DeployType.ShopBrand.getDesc() + "/" + newFileName);
			brandService.update(categoryDom);
			resetRedisDeployed(DeployType.ShopBrand, brandId);
			return new ModelAndView(new RedirectView(request.getContextPath() + "wbrand/detail.htm?brandId=" + brandId));
		}
		return new ModelAndView();

	}

	@RequestMapping(value = "/edit.htm")
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response, String brandId,
			BaseBrandDomain domain) {
		ModelAndView view = new ModelAndView("admin/shop/brand/edit");
		if (domain == null || domain.getId() == null) {
			// redirect
			Long parabrand = Long.valueOf(brandId);
			BaseBrandDomain brand = brandService.getById(parabrand);
			view.addObject("brand", brand);
			return view;
		} else {
			Answer<Object> r = new Answer<Object>();

			try {
				BaseBrandDomain brand = brandService.getById(domain.getId());
				BaseBrandDomain change = brand.compareTo(domain);
				change.setId(domain.getId());
				// edit
				domain.setName(null);// 此属性不可更新
				brandService.update(change);
				// update redis
				resetRedisDeployed(DeployType.ShopBrand, domain.getId());
				this.outText(response, JsonUtil.jsonFromObject(r));
			} catch (Exception e) {
				r.setCmd(-1);
				r.setMsg("System Error");
				this.outText(response, JsonUtil.jsonFromObject(r));
				e.printStackTrace();
			}
			return view;
		}
	}

	private Map<String, Object> asDynabean(Object obj) {
		if (null == obj) {
			return Maps.newHashMap();
		}

		return Reflecter.from(obj).asMap();
	}

	public void resetRedisDeployed(DeployType type, Long id) {
		if (deployRDao.isDeployed(type, id)) {
			deployRDao.setUndeployed(type, id);
		}
	}
}
